package com.toobigtofail.utility
{
	import Box2D.Dynamics.Contacts.b2Contact;
	import Box2D.Dynamics.b2Body;
	import Box2D.Dynamics.b2ContactListener;
	
	import com.toobigtofail.Game;
	import com.toobigtofail.enitities.BatShit;
	import com.toobigtofail.enitities.CavernWall;
	import com.toobigtofail.enitities.Enemy;
	import com.toobigtofail.enitities.Player;
	
	import fabulaexmachina.box2fp.Box2DEntity;
	
	public class ContactListener extends b2ContactListener
	{
		public function ContactListener()
		{
			super();
		}
		
		/**
		 * Called when two fixtures begin to touch.
		 */
		override public function BeginContact(contact:b2Contact):void {
			var e1:Box2DEntity = contact.GetFixtureA().GetBody().GetUserData();
			var e2:Box2DEntity = contact.GetFixtureB().GetBody().GetUserData();
			
			var player:Player = null;
			var enemy:Box2DEntity = null;
			if (e1.type == Player.TYPE && isEnemy(e2)) {
				player = e1 as Player;
				enemy = e2;
			}
			else if (isEnemy(e1) && e2.type == Player.TYPE) {
				player = e2 as Player;
				enemy = e1;
			}
			
			if (player && enemy) {
				if (player.isUsingPower() && enemy.type != "spike") {
					enemy.remove();
				}
				else {
					die(player);
				}
			}
		}
		
		private function isEnemy(e:Box2DEntity):Boolean {
			switch(e.type) {
				case "enemy":
				case BatShit.TYPE:
				case "spike":
					return true;
			}
			return false;
		}
		
		private function die(e:Box2DEntity):void {
			(e.world as Game).die();
		}
	}
}